// ==============================================
// 智能体问答系统 - 应用初始化
// ==============================================

import { App } from 'vue'
import { initializeServices } from '@/services'
import { initializeStores } from '@/stores'
import { initializePCInteractions } from '@/composables'
import { useChatStore } from '@/stores/chat'
import { useTaskStore } from '@/stores/task'
import { useMCPStore } from '@/stores/mcp'
import { useUIStore } from '@/stores/ui'
import { useChatService } from '@/services/chat'
import { useSSE } from '@/services/sse'
import { createDefaultShortcuts } from '@/composables/useShortcuts'

// 应用初始化配置
export interface AppInitConfig {
  apiBaseUrl?: string
  theme?: 'light' | 'dark' | 'auto'
  enableShortcuts?: boolean
  enableSSE?: boolean
  autoReconnect?: boolean
  debugMode?: boolean
}

// 默认配置
const DEFAULT_CONFIG: Required<AppInitConfig> = {
  apiBaseUrl: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1',
  theme: 'auto',
  enableShortcuts: true,
  enableSSE: true,
  autoReconnect: true,
  debugMode: import.meta.env.DEV
}

/**
 * 初始化应用程序
 */
export async function initializeApp(app: App, config: AppInitConfig = {}): Promise<void> {
  const finalConfig = { ...DEFAULT_CONFIG, ...config }
  
  console.log('🚀 开始初始化智能体问答系统...')
  
  try {
    // 1. 初始化服务层
    console.log('📡 初始化服务层...')
    initializeServices()
    
    // 2. 初始化状态管理
    console.log('📦 初始化状态管理...')
    initializeStores()
    
    // 3. 初始化PC端交互功能
    console.log('🖱️ 初始化PC端交互功能...')
    initializePCInteractions()
    
    // 4. 设置主题
    console.log('🎨 设置应用主题...')
    await initializeTheme(finalConfig.theme)
    
    // 5. 初始化快捷键
    if (finalConfig.enableShortcuts) {
      console.log('⌨️ 初始化快捷键...')
      await initializeShortcuts()
    }
    
    // 6. 初始化SSE连接
    if (finalConfig.enableSSE) {
      console.log('🔗 初始化SSE连接...')
      await initializeSSEConnection(finalConfig)
    }
    
    // 7. 加载初始数据
    console.log('📋 加载初始数据...')
    await loadInitialData()
    
    // 8. 设置全局错误处理
    console.log('🛡️ 设置错误处理...')
    setupErrorHandling(app, finalConfig.debugMode)
    
    console.log('✅ 应用初始化完成!')
    
  } catch (error) {
    console.error('❌ 应用初始化失败:', error)
    throw error
  }
}

/**
 * 初始化主题
 */
async function initializeTheme(theme: 'light' | 'dark' | 'auto'): Promise<void> {
  const uiStore = useUIStore()
  
  // 从本地存储恢复主题设置
  const savedTheme = localStorage.getItem('app-theme') as 'light' | 'dark' | null
  
  if (savedTheme) {
    uiStore.setTheme(savedTheme)
  } else if (theme === 'auto') {
    // 自动检测系统主题
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    uiStore.setTheme(prefersDark ? 'dark' : 'light')
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      if (localStorage.getItem('app-theme') === null) {
        uiStore.setTheme(e.matches ? 'dark' : 'light')
      }
    })
  } else {
    uiStore.setTheme(theme)
  }
  
  // 监听主题变化并保存到本地存储
  uiStore.$subscribe((mutation, state) => {
    if (mutation.storeId === 'ui' && 'theme' in mutation.payload) {
      localStorage.setItem('app-theme', state.theme)
      
      // 应用主题到HTML元素
      const htmlElement = document.documentElement
      if (state.theme === 'dark') {
        htmlElement.classList.add('dark')
      } else {
        htmlElement.classList.remove('dark')
      }
    }
  })
  
  // 立即应用当前主题
  const htmlElement = document.documentElement
  if (uiStore.theme === 'dark') {
    htmlElement.classList.add('dark')
  } else {
    htmlElement.classList.remove('dark')
  }
}

/**
 * 初始化快捷键
 */
async function initializeShortcuts(): Promise<void> {
  const chatStore = useChatStore()
  const taskStore = useTaskStore()
  const uiStore = useUIStore()
  
  const shortcuts = createDefaultShortcuts({
    sendMessage: () => {
      // 触发发送消息事件
      const event = new CustomEvent('shortcut:send-message')
      document.dispatchEvent(event)
    },
    newChat: async () => {
      const sessionId = await chatStore.createSession()
      chatStore.setCurrentSession(sessionId)
    },
    clearChat: () => {
      if (chatStore.currentSessionId) {
        chatStore.clearMessages()
      }
    },
    toggleSidebar: () => {
      uiStore.toggleSidebar()
    },
    focusInput: () => {
      const event = new CustomEvent('shortcut:focus-input')
      document.dispatchEvent(event)
    },
    showHelp: () => {
      uiStore.toggleHelpDialog()
    },
    saveChat: () => {
      if (chatStore.currentSessionId) {
        const sessionData = chatStore.exportSession()
        if (sessionData) {
          const blob = new Blob([JSON.stringify(sessionData, null, 2)], {
            type: 'application/json'
          })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `chat-session-${Date.now()}.json`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
        }
      }
    },
    openSettings: () => {
      uiStore.toggleSettingsDialog()
    },
    confirmTask: () => {
      if (taskStore.canExecute) {
        taskStore.confirmExecution()
      }
    },
    cancelExecution: () => {
      if (taskStore.isExecuting) {
        taskStore.cancelExecution()
      }
    }
  })
  
  // 注册全局快捷键
  const { registerShortcut } = await import('@/composables/useShortcuts')
  shortcuts.forEach(shortcut => {
    registerShortcut(shortcut)
  })
}

/**
 * 初始化SSE连接
 */
async function initializeSSEConnection(config: Required<AppInitConfig>): Promise<void> {
  const { connect, onStateChange } = useSSE()
  const chatStore = useChatStore()
  
  // 监听连接状态变化
  onStateChange((state) => {
    chatStore.updateConnectionStatus(state)
    console.log('SSE连接状态变化:', state)
  })
  
  // 尝试建立SSE连接
  try {
    const sseUrl = `${config.apiBaseUrl.replace('/api/v1', '')}/sse`
    await connect(sseUrl)
    console.log('SSE连接建立成功')
  } catch (error) {
    console.warn('SSE连接失败，将在需要时重新尝试:', error)
  }
}

/**
 * 加载初始数据
 */
async function loadInitialData(): Promise<void> {
  const mcpStore = useMCPStore()
  
  try {
    // 加载MCP服务列表
    await mcpStore.loadServices()
    console.log('MCP服务列表加载完成')
  } catch (error) {
    console.warn('加载MCP服务列表失败:', error)
  }
  
  // 创建默认会话
  try {
    const chatStore = useChatStore()
    const sessionId = await chatStore.createSession()
    chatStore.setCurrentSession(sessionId)
    console.log('默认会话创建完成')
  } catch (error) {
    console.warn('创建默认会话失败:', error)
  }
}

/**
 * 设置全局错误处理
 */
function setupErrorHandling(app: App, debugMode: boolean): void {
  // Vue错误处理
  app.config.errorHandler = (err, vm, info) => {
    console.error('Vue错误:', err)
    if (debugMode) {
      console.error('组件实例:', vm)
      console.error('错误信息:', info)
    }
    
    // 显示用户友好的错误提示
    showUserFriendlyError(err as Error)
  }
  
  // 全局未捕获错误
  window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error)
    if (debugMode) {
      console.error('错误详情:', event)
    }
    showUserFriendlyError(event.error)
  })
  
  // Promise未捕获错误
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason)
    if (debugMode) {
      console.error('Promise错误详情:', event)
    }
    showUserFriendlyError(event.reason)
  })
}

/**
 * 显示用户友好的错误提示
 */
function showUserFriendlyError(error: Error): void {
  const uiStore = useUIStore()
  
  let message = '出现了一个错误'
  
  if (error.message.includes('network') || error.message.includes('fetch')) {
    message = '网络连接出现问题，请检查网络连接'
  } else if (error.message.includes('timeout')) {
    message = '请求超时，请稍后重试'
  } else if (error.message.includes('401') || error.message.includes('unauthorized')) {
    message = '身份验证失败，请重新登录'
  } else if (error.message.includes('403') || error.message.includes('forbidden')) {
    message = '没有权限执行此操作'
  } else if (error.message.includes('404')) {
    message = '请求的资源不存在'
  } else if (error.message.includes('500')) {
    message = '服务器内部错误，请稍后重试'
  }
  
  uiStore.showNotification({
    type: 'error',
    title: '错误',
    message,
    duration: 5000
  })
}

/**
 * 应用清理函数
 */
export function cleanupApp(): void {
  console.log('🧹 清理应用资源...')
  
  // 断开SSE连接
  const { disconnect } = useSSE()
  disconnect()
  
  // 清理存储
  const chatStore = useChatStore()
  const taskStore = useTaskStore()
  const mcpStore = useMCPStore()
  
  chatStore.resetChat()
  taskStore.resetTasks()
  mcpStore.resetMCP()
  
  console.log('✅ 应用清理完成')
}

/**
 * 应用健康检查
 */
export async function healthCheck(): Promise<{
  status: 'healthy' | 'unhealthy'
  details: Record<string, any>
}> {
  const details: Record<string, any> = {}
  let overallStatus: 'healthy' | 'unhealthy' = 'healthy'
  
  try {
    // 检查API连接
    const { healthCheck } = await import('@/services/api')
    const apiHealth = await healthCheck()
    details.api = { status: 'healthy', ...apiHealth }
  } catch (error) {
    details.api = { status: 'unhealthy', error: (error as Error).message }
    overallStatus = 'unhealthy'
  }
  
  try {
    // 检查SSE连接
    const { getState } = useSSE()
    const sseState = getState()
    details.sse = { 
      status: sseState === 'connected' ? 'healthy' : 'unhealthy',
      state: sseState
    }
    if (sseState !== 'connected') {
      overallStatus = 'unhealthy'
    }
  } catch (error) {
    details.sse = { status: 'unhealthy', error: (error as Error).message }
    overallStatus = 'unhealthy'
  }
  
  // 检查存储状态
  const chatStore = useChatStore()
  const taskStore = useTaskStore()
  const mcpStore = useMCPStore()
  
  details.stores = {
    chat: {
      sessions: chatStore.sessionCount,
      currentSession: chatStore.hasCurrentSession
    },
    tasks: {
      totalTasks: taskStore.currentTasks.length,
      isExecuting: taskStore.isExecuting
    },
    mcp: {
      services: mcpStore.serviceCount
    }
  }
  
  return {
    status: overallStatus,
    details
  }
}

export default {
  initializeApp,
  cleanupApp,
  healthCheck
}